﻿
'*******************************************************************
' Program: Data Center Visio Rack Tool
' Author: Albert E Edlund
' Date:
'
' Purpose:
'
'
'*******************************************************************

Imports Microsoft.Practices.EnterpriseLibrary.Common
Imports Microsoft.Practices.EnterpriseLibrary.Data
Imports Microsoft.Practices.EnterpriseLibrary.ExceptionHandling
Imports Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging

Imports Microsoft.Office.Interop.Visio
Imports Microsoft.Office.Interop.Excel
Imports Microsoft.Office.Interop
Imports System.Runtime.InteropServices

Imports System.IO


Public Class frmvisRackSysMgmt


#Region " Properties and Declarations "

    Private _clsXmpl As clsExampleDraw
    Private _clsDrawData As clsDC_RackData


    '********* visio snippet vb.net vis0042vb ******************
    Private _drawingControl As AxMicrosoft.Office.Interop.VisOcx.AxDrawingControl
    Public Property drawingControl() As AxMicrosoft.Office.Interop.VisOcx.AxDrawingControl
        Get
            Return Me._drawingControl
        End Get
        Set(ByVal value As AxMicrosoft.Office.Interop.VisOcx.AxDrawingControl)
            Me._drawingControl = value
        End Set
    End Property


    '********* visio snippet vb.net vis0041vb ******************
    Private _drawingApplication As Microsoft.Office.Interop.Visio.Application
    Public Property drawingApplication() As Microsoft.Office.Interop.Visio.Application
        Get
            Return Me._drawingApplication
        End Get
        Set(ByVal value As Microsoft.Office.Interop.Visio.Application)
            If (value Is Nothing) Then
                Throw New System.ArgumentNullException("Value", _
                    "drawingApplication is Null.")
            End If
            Me._drawingApplication = value
        End Set
    End Property


    '********* visio snippet vb.net vis0043vb ******************
    Private _drawingDocument As Microsoft.Office.Interop.Visio.Document
    Public Property drawingDocument() As Microsoft.Office.Interop.Visio.Document
        Get
            Return Me._drawingDocument
        End Get
        Set(ByVal value As Microsoft.Office.Interop.Visio.Document)
            If (value Is Nothing) Then
                Throw New System.ArgumentNullException("Value", _
                    "drawingDocument is Null.")
            End If
            Me._drawingDocument = value
        End Set
    End Property


    '********* visio snippet vb.net vis0045vb ******************
    Private _drawingWindow As Microsoft.Office.Interop.Visio.Window
    Public Property drawingWindow() As Microsoft.Office.Interop.Visio.Window
        Get
            Return Me._drawingWindow
        End Get
        Set(ByVal value As Microsoft.Office.Interop.Visio.Window)
            If (value Is Nothing) Then
                Throw New System.ArgumentNullException("Value", _
                    "drawingWindow is Null.")
            End If
            Me._drawingWindow = value
        End Set
    End Property

    '********* visio snippet vb.net vis0044vb ******************
    Private _drawingPage As Microsoft.Office.Interop.Visio.Page
    Public Property drawingPage() As Microsoft.Office.Interop.Visio.Page
        Get
            Return Me._drawingPage
        End Get
        Set(ByVal value As Microsoft.Office.Interop.Visio.Page)
            If (value Is Nothing) Then
                Throw New System.ArgumentNullException("Value", _
                    "drawingPage is Null.")
            End If
            Me._drawingPage = value
        End Set
    End Property

#End Region

#Region " Constructor "


    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.

        drawingControl = drawctrlExample

        InitTheDrawingControl()

        _clsDrawData = New clsDC_RackData


        _clsXmpl = New clsExampleDraw(drawingApplication, drawingDocument, drawingPage)
        _clsXmpl.drawingApplication = drawingApplication
        _clsXmpl.drawingDocument = drawingDocument
        _clsXmpl.drawExampleRack()

    End Sub


    '********* visio snippet vb.net vis0049vb ******************
    ' Properties and Definitions
    Private Const defaultDocumentName As String = "DrawExampleDocument"
    Private Const defaultPageName As String = "DrawExample"

    Private Sub InitTheDrawingControl()

        Try

            '
            ' get the pointers
            '
            ' make sure the control does not change the pagesizebehavior
            Me.drawingControl.PageSizingBehavior = VisPageSizingBehaviors.visNeverResizePages

            Me.drawingWindow = Me.drawingControl.Window
            Me.drawingWindow.Activate()
            Me.drawingApplication = Me.drawingControl.Window.Application

            Me.drawingDocument = Me.drawingControl.Document
            Dim docSheet As Visio.Shape = Me.drawingDocument.DocumentSheet
            docSheet.NameU = defaultDocumentName
            Me.drawingDocument.DiagramServicesEnabled = VisDiagramServices.visServiceVersion140

            Me.drawingPage = Me.drawingControl.Window.Page
            Me.drawingPage.Name = defaultPageName
            Me.drawingPage.NameU = defaultPageName
            drawingWindow.Page = drawingPage

            Me.drawingApplication.Application.Settings.EnableAutoConnect = False
            Me.drawingApplication.OnDataChangeDelay = -2

            Me.drawingWindow.ShowGrid = False
            Me.drawingWindow.ShowPageTabs = True
            Me.drawingWindow.ShowRulers = False
            Me.drawingWindow.ShowScrollBars = True


        Catch com As COMException
            ' add com exception handler here
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If
        Catch ex As Exception
            ' add exception handler here
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub



#End Region

#Region " External get/save "




    '
    ' Reads a workbook and returns a collection of worksheet names as a 
    ' dictionary
    '
    Private Function readExcelWorksheetList _
        (ByVal strWorkbook As String) _
        As Dictionary(Of Int16, String)

        Dim dictReturn As Dictionary(Of Int16, String) = New Dictionary(Of Int16, String)
        Dim objExcel As Microsoft.Office.Interop.Excel.Application = Nothing
        Dim objWorkBook As Microsoft.Office.Interop.Excel.Workbook = Nothing
        Dim objWorkSheets As Microsoft.Office.Interop.Excel.Worksheet = Nothing

        Try

            If (strWorkbook Is Nothing) Then
                Throw New System.ArgumentNullException("strWorkbookValueIsNull", _
                    "Workbook is Null.")
                GoTo ExitFunction
            End If

            If File.Exists(strWorkbook) = False Then
                MsgBox("Workbook (" & strWorkbook & ") not found")
                GoTo ExitFunction
            End If

            Dim ExcelSheetName As String = ""
            objExcel = CreateObject("Excel.Application")
            objWorkBook = objExcel.Workbooks.Open(strWorkbook)
            Dim intX As Integer = 1
            For Each objWorkSheets In objWorkBook.Worksheets
                dictReturn.Add(intX, objWorkSheets.Name)
                intX = intX + 1
            Next

ExitFunction:

        Catch com As COMException
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If

        Finally

            objWorkSheets = Nothing
            objWorkBook = Nothing
            objExcel.Quit()
            objExcel = Nothing

        End Try

        Return dictReturn

    End Function

    '
    ' read a worksheet and return a datatable
    '
    Private Function readExcelWorksheet _
            (ByVal strWorkBook As String, _
            ByVal strWorkSheet As String) _
            As System.Data.DataTable


        Dim dtReturn As System.Data.DataTable = Nothing

        Try

            If (strWorkBook Is Nothing) _
                Or strWorkBook = "" Then
                Throw New System.ArgumentNullException("strWorkbookValueIsNull", _
                    "Workbook is Null.")
                GoTo ExitFunction
            End If

            If File.Exists(strWorkBook) = False Then
                MsgBox("Workbook (" & strWorkBook & ") not found")
                GoTo ExitFunction
            End If

            Dim DS As DataSet
            Dim MyCommand As OleDb.OleDbDataAdapter
            Dim MyConnection As OleDb.OleDbConnection
            Dim strConnection As String = "Provider=Microsoft.ACE.OLEDB.12.0;" _
                                          & "Data Source=" & strWorkBook & ";" _
                                          & "Extended Properties=" & """Excel 12.0 Xml;HDR=YES""" & ";"
            MyConnection = New OleDb.OleDbConnection(strConnection)
            MyCommand = New OleDb.OleDbDataAdapter( _
                         "select * from [" & strWorkSheet & "$]", MyConnection)
            DS = New System.Data.DataSet()
            MyCommand.Fill(DS)
            dtReturn = DS.Tables(0)
            dtReturn.TableName = strWorkSheet
            MyConnection.Close()

ExitFunction:

        Catch oledb As OleDbException
            '********* visio snippet vb.net visXXXX ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(oledb, "Database Policy")
            If (rethrow) Then
                Throw
            End If
        Catch ex As Exception
            '********* visio snippet vb.net visXXXX ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

        Return dtReturn

    End Function

    '
    ' 
    '
    Private Sub saveVisioDocumentDialog()



        Try

            Dim visDoc As Microsoft.Office.Interop.Visio.Document = Me.drawingDocument

            ' flag the document as one of ours
            Dim docsheet As Microsoft.Office.Interop.Visio.Shape = visDoc.DocumentSheet

            SaveFileDialog.Filter = "vsd files (*.vsd)|*.vsd|All files (*.*)|*.*"
            SaveFileDialog.FilterIndex = 1
            SaveFileDialog.RestoreDirectory = True

            Dim dlgResult As DialogResult = SaveFileDialog.ShowDialog

            If dlgResult = DialogResult.OK Then

                visDoc.SaveAsEx(SaveFileDialog.FileName, Microsoft.Office.Interop.Visio.tagVisOpenSaveArgs.visSaveAsWS + _
                                Microsoft.Office.Interop.Visio.tagVisOpenSaveArgs.visSaveAsListInMRU)

            Else

                MsgBox("Save Cancelled")

            End If

        Catch com As COMException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try


        System.GC.Collect()

    End Sub

 
    '
    '
    '
    Private Sub openVisioDocumentDialog()



        Try

            OpenFileDialog.InitialDirectory = "c:\"
            OpenFileDialog.FileName = "*.vsd"
            OpenFileDialog.Filter = "visio drawings (*.vsd)|*.vsd|All files (*.*)|*.*"
            OpenFileDialog.FilterIndex = 1
            OpenFileDialog.RestoreDirectory = True

            Dim strPath As String = ""
            Dim dlgResult As System.Windows.Forms.DialogResult = OpenFileDialog.ShowDialog

            If dlgResult = System.Windows.Forms.DialogResult.OK Then

                Me.drawingControl.Src = OpenFileDialog.FileName

                Me.drawingWindow = Me.drawingControl.Window
                Me.drawingApplication = Me.drawingControl.Window.Application
                Me.drawingDocument = Me.drawingApplication.ActiveDocument
                Me.drawingPage = Me.drawingApplication.ActivePage

                ' flag it as already having been saved
                Me.drawingDocument.Saved = True

            End If

        Catch com As COMException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub





#End Region

#Region " Form Events "

    '
    '
    '
    Protected Overrides Sub Finalize()

        If _clsXmpl IsNot Nothing Then
            _clsXmpl = Nothing
        End If

        ' flag it as saved
        _drawingDocument.Saved = True
        NullAndRelease(_drawingPage)
        If _drawingPage IsNot Nothing Then
            _drawingPage = Nothing
        End If
        NullAndRelease(_drawingDocument)
        If _drawingDocument IsNot Nothing Then
            _drawingDocument = Nothing
        End If
        _drawingWindow = Nothing
        _drawingApplication.Quit()

        MyBase.Finalize()

    End Sub


    '********* visio snippet vb.net vis0098vb ******************
    Private Sub NullAndRelease(ByVal runtimeObject As Object)

        Try

            If Not (runtimeObject Is Nothing) Then

                ' The RCW's reference count gets incremented each time the
                ' COM pointer is passed from unmanaged to managed code.
                ' Call ReleaseComObject in a loop until it returns 0 to be
                ' sure that the underlying COM object gets released.
                Dim i As Integer
                Do
                    i = System.Runtime.InteropServices.Marshal. _
                        ReleaseComObject(runtimeObject)
                Loop While i > 0
            End If
        Finally
            runtimeObject = Nothing
        End Try
    End Sub


    '
    '
    '
    Private Sub ExitToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click

        Me.Close()

    End Sub

    '
    ' ICMP / PING testing
    '
    Private Sub ICMPToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ICMPToolStripMenuItem.Click


        addNetworkProperties()

        Dim frmPing As frmICMPMgmt = New frmICMPMgmt(Me.drawingApplication, Me.drawingDocument)
        Dim strIpAddress As String = getSelectedIp()
        frmPing.selectedIP = strIpAddress
        frmPing.drawingApplication = drawingApplication
        frmPing.drawingDocument = drawingApplication.ActiveDocument
        frmPing.drawingPage = drawingApplication.ActivePage
        frmPing.ShowDialog()
        frmPing.Dispose()
        frmPing = Nothing



    End Sub

    '
    ' SNMP QUERIES
    '
    Private Sub SNMPToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SNMPToolStripMenuItem.Click

        addNetworkProperties()

        Dim frmSnmp As frmSNMPMgmt = New frmSNMPMgmt
        Dim strIpAddress As String = getSelectedIp()
        frmSnmp.ipAddress = strIpAddress
        frmSnmp.ShowDialog()
        frmSnmp.Dispose()
        frmSnmp = Nothing

    End Sub

    '
    ' WMI QUERIES
    '
    Private Sub WMIToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles WMIToolStripMenuItem.Click

        addNetworkProperties()

        Dim frmWmi As frmWkstMgmt = New frmWkstMgmt
        frmWmi.ShowDialog()
        frmWmi.Dispose()
        frmWmi = Nothing


    End Sub

    '
    ' TELNET / SSH
    '
    Private Sub TelnetSSHToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles TelnetSSHToolStripMenuItem.Click

        ' need to ensure that the ip address is in the shape
        addNetworkProperties()

        ' get the ip address from the selected shpae
        Dim strIpAddress As String = getSelectedIp()

        sshTelnetToTarget(strIpAddress)


    End Sub

    '
    ' REMOTE DESKTOP
    '
    Private Sub RemoteDesktopToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles RemoteDesktopToolStripMenuItem.Click

        addNetworkProperties()

        Dim strIpAddress As String = getSelectedIp()
        connectMsTsc(strIpAddress)

    End Sub

    '
    '
    '
    Private Sub SaveToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SaveToolStripMenuItem.Click
        saveVisioDocumentDialog()
    End Sub


#End Region

#Region " Methods "


    '
    ' when we call a function that requires network properties we make
    ' a point of ensuring they are loaded into the shapes that are selected
    '
    Private Sub addNetworkProperties()

        Dim visSelected As Microsoft.Office.Interop.Visio.Selection
        Dim visShape As Microsoft.Office.Interop.Visio.Shape

        ' just to make sure
        Me.drawingWindow = Me.drawctrlExample.Window
        Me.drawingPage = Me.drawctrlExample.Window.Application.ActivePage
        Dim strPageName As String = Me.drawingPage.Name
        ' we do not need to load the properties for the example drawing
        If strPageName = "DrawExample" Then Exit Sub

        visSelected = Me.drawingWindow.Selection
        If 0 < visSelected.Count Then
            For Each visShape In visSelected
                _clsDrawData.loadAttrNetVisioProperties(visShape)
            Next visShape
        End If


    End Sub


    '
    ' get selected shape
    '
    Private Function getSelectedIp() As String

        Dim strSelected As String = ""
        Dim visWin As Microsoft.Office.Interop.Visio.Window = Me.drawctrlExample.Window
        Dim visSel As Microsoft.Office.Interop.Visio.Selection = visWin.Selection
        If visSel.Count = 1 Then
            Dim visShape As Microsoft.Office.Interop.Visio.Shape = visSel(1)
            If visShape.CellExists("prop.attrnetIpAddress", False) = True Then
                Dim visCell As Microsoft.Office.Interop.Visio.Cell = visShape.Cells("prop.attrnetIpAddress")
                strSelected = visCell.ResultStr("")
            End If
        End If

        Return strSelected

    End Function

    '
    '   telnet to target
    '
    Private Sub sshTelnetToTarget(ByVal strIpAddress As String)

        'make sure the shape data is in the shape
        addNetworkProperties()

        ' the path_ssh is hardcoded for the Vandyke software
        Dim strCommand As String = My.Settings.path_ssh_x64 & "securecrt "
        strCommand = strCommand & strIpAddress
        Microsoft.VisualBasic.Interaction.Shell(strCommand, AppWinStyle.NormalFocus)


    End Sub

    '
    '   terminal services to target
    '
    Private Sub connectMsTsc(ByVal strIpAddress As String)

        Dim strCommand As String = "c:\windows\system32\mstsc.exe /v:"
        strCommand = strCommand & strIpAddress
        strCommand = strCommand & " /console"

        Microsoft.VisualBasic.Interaction.Shell(strCommand)

    End Sub





#End Region



End Class
